package com.powergisol.gis.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.powergisol.gis.entity.TabService;
import com.powergisol.gis.service.FallBackService;
import com.powergisol.gis.service.MondbDataService;
import com.powergisol.gis.service.TabDataService;
import com.powergisol.gis.util.DataChangeUtil;
import com.powergisol.gis.util.FileRead;
import com.powergisol.gis.util.PropertyUtil;
import com.powergisol.gis.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.powergisol.gis.vo.B3DMJsonData;
import com.powergisol.gis.vo.CRSInfo;
import com.powergisol.gis.vo.FeatureType;
import com.powergisol.gis.vo.LOBJsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Date: 2019/9/3  14:44
 * Description:获取服务属性
 */
@RestController
@RequestMapping(value = "gis")
@Api(description = "获取服务属性" ,value = "获取服务属性")
public class TabLayerController {
    private static Logger logger = LoggerFactory.getLogger(TabLayerController.class);
    @Autowired
    private TabDataService tabDataService;
    @Autowired
    private FallBackService fallBackService;

    @Autowired
    private MondbDataService mondbDataService;

//    @Value("${file-url}")
//    private String fileUrl;
//    @Value("${style-url}")
//    private String styleUrl;


    @RequestMapping(value = "getLayerTable",method = RequestMethod.POST)
    public Result getLayerTable(String name,Integer page,Integer limit){
        Result result1 = new Result();
        TabService tabService = tabDataService.getByName(name);
        if(tabService.getState()!=1 || null == tabService.getFileUrl()){
            logger.error("服务不可用={},状态不为1或fileUrl为空",name);
            return result1.failure(-1,"服务不可用");
        }
        String userDir = System.getProperty("user.dir");
        userDir = userDir.substring(0,userDir.lastIndexOf(File.separator));
        logger.info("getLayerTable 参数={},{},{},{}", name,tabService.getFileUrl(),userDir+File.separator+"serviceData"+File.separator+"style"+File.separator+tabService.getStyleUrl(),tabService.getTitle());
        String result = fallBackService.getLayerTable(name,tabService.getFileUrl(),userDir+File.separator+"serviceData"+File.separator+"style"+File.separator+tabService.getStyleUrl(),tabService.getTitle());
        if(null == result){
            logger.error("获取 table 属性失败={}",name);
            return result1.failure(403,"获取 table 失败");
        }
        List<Map<String, Object>> list = toListMap(result);

//        PageHelper.startPage(null==page?1:page, null==limit?20:limit);
//        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);

        result1.setData(list);

        return result1;
    }
    private List<Map<String, Object>> toListMap(String json) {
        List<Object> list = JSON.parseArray(json);
        List<Map<String, Object>> listw = new ArrayList<>();
        for (Object object : list) {
            Map<String, Object> ret = (Map<String, Object>) object;
            listw.add(ret);
        }
        return listw;
    }


    @RequestMapping(value = "getLayerTableData",method = RequestMethod.POST)
    public Result getLayerTable(Integer index,String name){
        Result result1 = new Result();
        TabService tabService = tabDataService.getByName(name);
        if(tabService.getState()!=1 || null == tabService.getFileUrl()){
            logger.error("服务不可用={},状态不为1或fileUrl为空",name);
            return result1.failure(-1,"服务不可用");
        }
        String userDir = System.getProperty("user.dir");
        userDir = userDir.substring(0,userDir.lastIndexOf(File.separator));
        String result = fallBackService.getLayerTableData(name,index,tabService.getFileUrl(),userDir+File.separator+"serviceData"+File.separator+"style"+File.separator+tabService.getStyleUrl(),tabService.getTitle());
        if(null == result){
            logger.error("获取table index 属性失败={}",name);
            return result1.failure(403,"获取 table index 失败");
        }
        result1.setData(result);
        return result1;
    }

    @PostMapping("getLayer")
    @ApiOperation(value = "获取坐标系、原生坐标范围、数据属性等", notes = "获取坐标系、原生坐标范围、数据属性等")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "name", value = "服务名称", defaultValue = "1", required = true, paramType = "query")
    })
    public Result getLayer(String name){
        Result result1 = new Result();
        Map<String,Object> map = new HashMap<>();
        TabService tabService = tabDataService.getByName(name);
        if(tabService.getState()!=1 || null == tabService.getFileUrl()){
            logger.info("服务不可用={},状态不为1或fileUrl为空",name);
            return result1.failure(-1,"服务不可用");
        }
        switch (tabService.getServiceType()){
            //调用接口获取文件
            case 1://影像缓存文件（*.tif）
            case 3://高程缓存文件（*.tif）
            case 4://矢量缓存文件（*.shp）
                String userDir = System.getProperty("user.dir");
                userDir = userDir.substring(0,userDir.lastIndexOf(File.separator));
                String fileUrl1 = tabService.getFileUrl();
                if("terrain".equals(tabService.getChangeType())){
                    fileUrl1 = tabService.getOriginUrl();
                    if(null == fileUrl1){
                        fileUrl1 = userDir+File.separator+"serviceData"+File.separator+"formal"+File.separator+"tif"+File.separator+tabService.getUuid()+File.separator+"layer.tif";
                    }
                }
                logger.info("获取 layer 属性={},{},{},{}",name,fileUrl1,userDir+File.separator+"serviceData"+File.separator+"style"+File.separator+tabService.getStyleUrl(),tabService.getTitle());
                String result = fallBackService.getLayer(name,fileUrl1,userDir+File.separator+"serviceData"+File.separator+"style"+File.separator+tabService.getStyleUrl(),tabService.getTitle());
                if(null == result){
                    logger.error("获取 layer 属性失败={}",name);
                    return result1.failure(403,"获取服务属性失败");
                }
                JSONObject object = JSONObject.parseObject(result);
                FeatureType featureType = DataChangeUtil.jsonToEntity(object);
                if(null == featureType){
                    return result1.failure(404,"服务不存在");
                }
                map.put("name",name);
                map.put("featureType",featureType);
                break;
            case 2://高程缓存文件（*.terrain）
                break;
            case 5://b3dm三维模型文件（*.json）
                String b3dmUrl = mondbDataService.getFileUrl(tabService.getFileUrl(),tabService.getUuid());
                ///String b3dmUrl = tabService.getFileUrl();
                if(null == b3dmUrl){
                    break;
                }
                FeatureType b3dmType = DataChangeUtil.b3dmToEntity(b3dmUrl);
                map.put("name",name);
                map.put("featureType",b3dmType);
                break;
            case 8://lob三维模型文件（*.json）
                String lobUrl = mondbDataService.getFileUrl(tabService.getFileUrl(),tabService.getUuid());
                //String lobUrl = tabService.getFileUrl();
                if(null == lobUrl){
                    break;
                }
                FeatureType lobType = DataChangeUtil.lobToEntity(lobUrl);
                map.put("name",name);
                map.put("featureType",lobType);
                break;
            case 6://osgb三维模型文件（*.xml）
                String changeType = tabService.getChangeType();
                String osgbUrl = mondbDataService.getFileUrl(tabService.getFileUrl(),tabService.getUuid());
                //String osgbUrl = tabService.getFileUrl();
                if(null == osgbUrl){
                    break;
                }
                FeatureType osgbType = null;
                switch (changeType){
                    case "b3dm":
                        osgbType = DataChangeUtil.osgbTb3dmToEntity(osgbUrl);
                        break;
                    case "lob" :
                    case "pld" :
                        osgbType = DataChangeUtil.lobToEntity(osgbUrl);
                        break;
                    default :
                        break;
                }
                map.put("name",name);
                map.put("featureType",osgbType);
                break;
            case 7://obj三维模型文件（*.obj）
                break;
            default:
                break;
        }
        result1.setData(map);
        return result1;
    }

}
